﻿using Furion.RemoteRequest.Extensions;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Furion.CMS.Web.Core
{
    /// <summary>
    /// 创建服务端渲染的ReactApp视图模型
    /// </summary>
    public class CreateReactAppViewModel
    {
        private static readonly Regex _parser = new(
            @"<head>(?<HeadContent>.*)</head>\s*<body>(?<BodyContent>.*)</body>",
            RegexOptions.IgnoreCase | RegexOptions.Singleline);

        /// <summary>
        /// head 内容
        /// </summary>
        public string HeadContent { get; set; }
        /// <summary>
        /// body 内容
        /// </summary>
        public string BodyContent { get; set; }

        public CreateReactAppViewModel(HttpContext context)
        {
            var reactAppUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.PathBase}/index.html";
            //var request = WebRequest.Create(
            //    context.Request.Scheme + "://" + context.Request.Host +
            //    context.Request.PathBase + "/index.html");
            //var response = request.GetResponse();
            //var stream = response.GetResponseStream();
            var stream = new HttpClient().GetStreamAsync(reactAppUrl).Result;
            var reader = new StreamReader(
                stream ?? throw new InvalidOperationException(
                "The create-react-app build output could not be found in " +
                "/ClientApp/dist. You probably need to run npm run build. " +
                "For local development, consider npm start."));

            var htmlFileContent = reader.ReadToEnd();
            var matches = _parser.Matches(htmlFileContent);

            if (matches.Count != 1)
            {
                throw new InvalidOperationException(
                    "The create-react-app build output does not appear " +
                    "to be a valid html file.");
            }

            var match = matches[0];

            HeadContent = match.Groups["HeadContent"].Value;
            BodyContent = match.Groups["BodyContent"].Value;
        }
    }
}
